package com.wizz.trade.information.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wizz.trade.common.PageVo;
import com.wizz.trade.excel.ExcelBuildParams;
import com.wizz.trade.information.dto.CompanyDto;
import com.wizz.trade.information.dto.page.OtherCompanyPageDto;
import com.wizz.trade.information.dto.page.OurCompanyPageDto;
import com.wizz.trade.information.entity.Bankinfo;
import com.wizz.trade.information.entity.Company;
import com.wizz.trade.information.entity.Companydept;
import com.wizz.trade.information.service.BankinfoService;
import com.wizz.trade.information.service.CompanyService;
import com.wizz.trade.common.ResponseResult;
import com.wizz.trade.common.constant.StatusCode;
import com.wizz.trade.information.service.CompanydeptService;
import com.wizz.trade.information.vo.CompanyVo;
import com.wizz.trade.information.vo.CompanySimpleInfoVo;
import com.wizz.trade.util.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 资料模块/公司（账套）信息
 */
@RestController
@RequestMapping("/company")
public class CompanyController {

    @Resource
    private CompanyService companyService;

    @Resource
    private BankinfoService bankinfoService;

    @Resource
    private CompanydeptService companydeptService;


    /**
     * 添加操作
     *
     * @param
     * @return
     */
    @PostMapping
    @PreAuthorize("hasAuthority('设置公司账套部门')")
    public ResponseResult<String> addCompany(@RequestBody CompanyDto companyDto) {
        Company company = new Company();
        BeanUtils.copyProperties(companyDto, company);
        companyService.addCompany(company);
        return new ResponseResult<>(StatusCode.OK, "添加成功");
    }

    /**
     * 更新（编辑）操作
     *
     * @param id
     * @return
     */

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('设置公司账套部门')")
    public ResponseResult<String> updateCompany(@RequestBody CompanyDto companyDto, @PathVariable("id") Integer id) {
        Company company = new Company();
        BeanUtils.copyProperties(companyDto, company);
        company.setId(id);
        companyService.updateCompany(company);
        return new ResponseResult<>(StatusCode.OK, "修改成功");
    }

    /**
     * 删除公司（撤销）操作
     *
     *
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('设置公司账套部门')")
    public ResponseResult deleteCompany(@PathVariable("id") Integer id) {
        //删除该账套（公司）
        companyService.deleteCompany(id);


        //删除该公司的所有银行
        QueryWrapper<Bankinfo> bankinfoQueryWrapper = new QueryWrapper<>();
        bankinfoQueryWrapper.eq("company", id);
        bankinfoService.remove(bankinfoQueryWrapper);

        //如果单位类型不是本公司账套，还要删除对应的部门信息

        if (companyService.getById(id).getType() != 1) {
            QueryWrapper<Companydept> companydeptQueryWrapper = new QueryWrapper<>();
            companydeptQueryWrapper.eq("company", id);
            companydeptService.remove(companydeptQueryWrapper);
        }

        return new ResponseResult<>(StatusCode.OK, "删除成功");
    }

    /**
     * 分页刷新、条件查询：本公司
     *
     * @param ourCompanyPageDto
     * @return
     */
    @GetMapping("/page/our")
    @PreAuthorize("hasAuthority('设置公司账套部门')")

    public ResponseResult<PageVo<CompanyVo>> listOur(OurCompanyPageDto ourCompanyPageDto) {
        PageVo<Company> rawPage = companyService.getPageOur(ourCompanyPageDto);
        List<Company> data = rawPage.getData();
        List<CompanyVo> dataVo = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            CompanyVo companyVo = new CompanyVo();
            BeanUtils.copyProperties(data.get(i), companyVo);
            String ladmet = data.get(i).getLadmet() == 0 ? "系统" : "人工";
            companyVo.setLadmet(ladmet);
            dataVo.add(companyVo);
        }
        return new ResponseResult<>(StatusCode.OK, new PageVo<>(rawPage.getPages(), rawPage.getTotal(), dataVo));
    }

    /**
     * 分页刷新、条件查询：其他公司（部门）
     *
     * @param otherCompanyPageDto
     * @return
     */
    @GetMapping("/page/others")
    @PreAuthorize("hasAuthority('设置往来单位资料、部门')")
    public ResponseResult<PageVo<CompanyVo>> listOthers(OtherCompanyPageDto otherCompanyPageDto) {
        PageVo<Company> rawPage = companyService.getPageOthers(otherCompanyPageDto);
        List<Company> data = rawPage.getData();
        List<CompanyVo> dataVo = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            CompanyVo companyVo = new CompanyVo();
            BeanUtils.copyProperties(data.get(i), companyVo);
            String ladmet = data.get(i).getLadmet() == 0 ? "系统" : "人工";
            companyVo.setLadmet(ladmet);
            dataVo.add(companyVo);
        }
        return new ResponseResult<>(StatusCode.OK, new PageVo<>(rawPage.getPages(), rawPage.getTotal(), dataVo));
    }


    /**
     * 导出账套信息+银行信息+部门联系人信息
     *
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/export/our")
    @PreAuthorize("hasAuthority('设置公司账套部门')")

    public ResponseResult<String> exportOur(HttpServletResponse response) {
        String filename = "公司（账套）信息表.xlsx";
        List<Company> companies = companyService.getAll();
        ExcelBuildParams params = new ExcelBuildParams();
        params.setClazz(Company.class);
        params.setData(companies);
        params.setFileName(filename);
        ExcelUtil.exportExcelWithList(response, params);
        return new ResponseResult<>(StatusCode.OK, "导出数据成功");
    }


    /**
     * 导出贸易商基础资料
     *
     * @param response
     * @return
     */
    @GetMapping("/export/trafficker")
    @PreAuthorize("hasAuthority('设置往来单位资料、部门')")
    public ResponseResult<String> exportTrafficker(HttpServletResponse response) {
        // TODO: 2023/4/28
        return null;
    }

    /**
     * 导出所选单位的所有银行账号记录
     *
     * @param response
     * @param id       要导出的银行的单位的id
     * @return
     */
    @GetMapping("/export/others/bank/{id}")
    @PreAuthorize("hasAuthority('设置往来单位资料、部门')")
    public ResponseResult<String> exportOthersBank(HttpServletResponse response, @PathVariable Integer id) {
        // TODO: 2023/4/28
        return null;
    }


    /**
     * 导出所选单位的所有部门记录
     *
     * @param response
     * @param id       要导出的部门的单位的id
     * @return
     */
    @GetMapping("/export/others/dept/{id}")
    @PreAuthorize("hasAuthority('设置往来单位资料、部门')")

    public ResponseResult<String> exportOthersDept(HttpServletResponse response, @PathVariable Integer id) {
        // TODO: 2023/4/28
        return null;
    }

    /**
     * 根据type列出所有相应类型所有公司
     * 1本公司账套、2贸易商、3仓库、4期货公司、5海关、6税务机关
     *
     * @param type
     * @return
     */
    @GetMapping("/list/others")
    @PreAuthorize("hasAuthority('设置往来单位资料、部门')")
    public ResponseResult<List<CompanySimpleInfoVo>> listOthers(Byte type) {
        ArrayList<CompanySimpleInfoVo> resList = new ArrayList<>();

        QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
        companyQueryWrapper.eq("type", type);
        List<Company> companies = companyService.list(companyQueryWrapper);
        for (Company company : companies) {
            resList.add(new CompanySimpleInfoVo(company.getId(), company.getType(), company.getFullname()));

        }
        return new ResponseResult<>(StatusCode.OK, resList);
    }

    /**
     * 查询账套信息的下拉框选项
     * @return 键值对
     */
    @GetMapping("/options/1")
    public ResponseResult<List<Map<Integer, String>>> getLedgerOptions(){
        return new ResponseResult<>(StatusCode.OK, companyService.getLedgerOptions());
    }

    /**
     * 查询其他公司信息的下拉框选线
     * @return 键值对
     */
    @GetMapping("/options/2")
    public ResponseResult<List<Map<Integer, String>>> getCompanyOptions(){
        return new ResponseResult<>(StatusCode.OK, companyService.getCompanyOptions());
    }

}
